package com.demo.service.impl.login;

import com.demo.domain.MailBean;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

//发送邮箱工具类
@Service
public class JavaMailutil {

    /**
     * 发送简单的文字邮件
     */
    public synchronized static void Sendmail(MailBean mailBean) throws Exception {
        Properties prop = new Properties();
        prop.setProperty("mail.host", mailBean.getHost());
        prop.setProperty("mail.transport.protocol", mailBean.getProtocol());
        prop.setProperty("mail.smtp.auth", "true");
        //使用JavaMail发送邮件的5个步骤
        //1、创建session
        Session session = Session.getInstance(prop);
        //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
        // session.setDebug(true);

        //2、通过session得到transport对象
        Transport ts = session.getTransport();
        //3、使用邮箱的用户名和密码连上邮件服务器，发送邮件时，发件人需要提交邮箱的用户名和密码给smtp服务器，用户名和密码都通过验证之后才能够正常发送邮件给收件人。
        ts.connect(mailBean.getHost(), mailBean.getUserName(), mailBean.getPassword());
        //4、创建邮件
        Message  message=null;
        if(mailBean.getType()==1){
            message = createSimpleMail(session,mailBean);
        }
        if(mailBean.getType()==2){
            message = createAttachMail(session,mailBean);
        }

        //5、发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
    }

    /**
     * @Method: createSimpleMail
     * @Description: 创建一封只包含文本的邮件
     * @Anthor:孤傲苍狼
     *
     * @param session
     * @return
     * @throws Exception
     */
    public static MimeMessage createSimpleMail(Session session,MailBean mailBean)
            throws Exception {
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress(mailBean.getFromUser()));
        //指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailBean.getToUser()));
        //邮件的标题
        message.setSubject(mailBean.getTitel());
        //邮件的文本内容
        message.setContent(mailBean.getContent(), "text/html;charset=UTF-8");
        //返回创建好的邮件对象
        return message;
    }
    /**
     * @Method: createImageMail
     * @Description: 生成一封邮件正文带图片的邮件
     * @Anthor:孤傲苍狼
     *
     * @param session
     * @return
     * @throws Exception
     */
    public static MimeMessage createImageMail(Session session,MailBean mailBean) throws Exception {
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress(mailBean.getFromUser()));
        //指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailBean.getToUser()));
        //邮件标题
        message.setSubject(mailBean.getTitel());

        // 准备邮件数据
        // 准备邮件正文数据
        MimeBodyPart text = new MimeBodyPart();
        text.setContent(mailBean.getContent(), "text/html;charset=UTF-8");
        // 准备图片数据
        MimeBodyPart image = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource(mailBean.getFiles()[0]));
        image.setDataHandler(dh);
        image.setContentID("xxx.jpg");
        // 描述数据关系
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text);
        mm.addBodyPart(image);
        mm.setSubType("related");

        message.setContent(mm);
        message.saveChanges();
        //将创建好的邮件写入到E盘以文件的形式进行保存
        message.writeTo(new FileOutputStream("C:\\ImageMail.eml"));
        //返回创建好的邮件
        return message;
    }

    /**
     * @Method: createAttachMail
     * @Description: 创建一封带附件的邮件
     * @Anthor:孤傲苍狼
     *
     * @param session
     * @return
     * @throws Exception
     */
    public static MimeMessage createAttachMail(Session session ,MailBean mailBean) throws Exception{
        MimeMessage message = new MimeMessage(session);

        //设置邮件的基本信息
        //发件人
        message.setFrom(new InternetAddress(mailBean.getFromUser()));
        //收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailBean.getToUser()));
        //邮件标题
        message.setSubject(mailBean.getTitel());

        //创建邮件正文，为了避免邮件正文中文乱码问题，需要使用charset=UTF-8指明字符编码
        MimeBodyPart text = new MimeBodyPart();
        text.setContent(mailBean.getContent(), "text/html;charset=UTF-8");

        if(mailBean.getFiles().length!=0){
            //创建邮件附件
            MimeBodyPart attach = new MimeBodyPart();
            DataHandler dh = new DataHandler(new FileDataSource(mailBean.getFiles()[0]));
            attach.setDataHandler(dh);
            attach.setFileName(dh.getName());  //

            //创建容器描述数据关系
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(text);
            mp.addBodyPart(attach);
            mp.setSubType("mixed");
            message.setContent(mp);
            message.saveChanges();
            //将创建的Email写入到E盘存储
            message.writeTo(new FileOutputStream("C:\\attachMail.eml"));

        }
        //返回生成的邮件
        return message;

    }

    /**
     * @Method: createMixedMail
     * @Description: 生成一封带附件和带图片的邮件
     * @Anthor:孤傲苍狼
     *
     * @param session
     * @return
     * @throws Exception
     */
    public static MimeMessage createMixedMail(Session session,MailBean mailBean) throws Exception {
        //创建邮件
        MimeMessage message = new MimeMessage(session);

        //设置邮件的基本信息
        message.setFrom(new InternetAddress(mailBean.getFromUser()));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailBean.getToUser()));
        message.setSubject(mailBean.getTitel());

        //正文
        MimeBodyPart text = new MimeBodyPart();
        text.setContent(mailBean.getContent(),"text/html;charset=UTF-8");

        //附件1
        MimeBodyPart attach = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource(mailBean.getFiles()[0]));
        attach.setDataHandler(dh);
        attach.setFileName(dh.getName());


        //描述关系:正文和图片
        MimeMultipart mp1 = new MimeMultipart();
        mp1.addBodyPart(text);
        mp1.setSubType("related");

        //描述关系:正文和附件
        MimeMultipart mp2 = new MimeMultipart();
        mp2.addBodyPart(attach);

        //代表正文的bodypart
        MimeBodyPart content = new MimeBodyPart();
        content.setContent(mp1);
        mp2.addBodyPart(content);
        mp2.setSubType("mixed");

        message.setContent(mp2);
        message.saveChanges();

        message.writeTo(new FileOutputStream("C:\\MixedMail.eml"));
        //返回创建好的的邮件
        return message;
    }

    public void code(int code,String mail){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        String shijian=df.format(new Date());// new Date()为获取当前系统时间
        MailBean mailBean=new MailBean();
        mailBean.setAuth(true)
                .setHost("smtp.qq.com")
                .setProtocol("smtp")
                .setType(1)
                .setContent("<head>\n" +
                        "    <base target=\"_blank\" />\n" +
                        "    <style type=\"text/css\">::-webkit-scrollbar{ display: none; }</style>\n" +
                        "    <style id=\"cloudAttachStyle\" type=\"text/css\">#divNeteaseBigAttach, #divNeteaseBigAttach_bak{display:none;}</style>\n" +
                        "    <style id=\"blockquoteStyle\" type=\"text/css\">blockquote{display:none;}</style>\n" +
                        "    <style type=\"text/css\">\n" +
                        "        body{font-size:14px;font-family:arial,verdana,sans-serif;line-height:1.666;padding:0;margin:0;overflow:auto;white-space:normal;word-wrap:break-word;min-height:100px}\n" +
                        "        td, input, button, select, body{font-family:Helvetica, 'Microsoft Yahei', verdana}\n" +
                        "        pre {white-space:pre-wrap;white-space:-moz-pre-wrap;white-space:-pre-wrap;white-space:-o-pre-wrap;word-wrap:break-word;width:95%}\n" +
                        "        th,td{font-family:arial,verdana,sans-serif;line-height:1.666}\n" +
                        "        img{ border:0}\n" +
                        "        header,footer,section,aside,article,nav,hgroup,figure,figcaption{display:block}\n" +
                        "        blockquote{margin-right:0px}\n" +
                        "    </style>\n" +
                        "</head>\n" +
                        "<body tabindex=\"0\" role=\"listitem\">\n" +
                        "<table width=\"700\" border=\"0\" align=\"center\" cellspacing=\"0\" style=\"width:700px;\">\n" +
                        "    <tbody>\n" +
                        "    <tr>\n" +
                        "        <td>\n" +
                        "            <div style=\"width:700px;margin:0 auto;border-bottom:1px solid #ccc;margin-bottom:30px;\">\n" +
                        "                <table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"700\" height=\"39\" style=\"font:12px Tahoma, Arial, 宋体;\">\n" +
                        "                    <tbody><tr><td width=\"210\"></td></tr></tbody>\n" +
                        "                </table>\n" +
                        "            </div>\n" +
                        "            <div style=\"width:680px;padding:0 10px;margin:0 auto;\">\n" +
                        "                <div style=\"line-height:1.5;font-size:14px;margin-bottom:25px;color:#4d4d4d;\">\n" +
                        "                    <strong style=\"display:block;margin-bottom:15px;\">尊敬的用户：<span style=\"color:#f60;font-size: 16px;\"></span>您好！</strong>\n" +
                        "                    <strong style=\"display:block;margin-bottom:15px;\">\n" +
                        "                        您正在进行<span style=\"color: red\">邮箱验证</span>操作，请在验证码输入框中输入：<span style=\"color:#f60;font-size: 24px\">"+code+"</span>，以完成操作。\n" +
                        "                    </strong>\n" +
                        "                </div>\n" +
                        "                <div style=\"margin-bottom:30px;\">\n" +
                        "                    <small style=\"display:block;margin-bottom:20px;font-size:12px;\">\n" +
                        "                        <p style=\"color:#747474;\">\n" +
                        "                            注意：此操作可能会修改您的密码、登录邮箱或绑定手机。如非本人操作，请及时登录并修改密码以保证帐户安全\n" +
                        "                            <br>（工作人员不会向你索取此验证码，请勿泄漏！)\n" +
                        "                        </p>\n" +
                        "                    </small>\n" +
                        "                </div>\n" +
                        "            </div>\n" +
                        "            <div style=\"width:700px;margin:0 auto;\">\n" +
                        "                <div style=\"padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;\">\n" +
                        "                    <p>此为系统邮件，请勿回复<br>\n" +
                        "                        请保管好您的邮箱，避免账号被他人盗用\n" +
                        "                    </p>\n" +
                        "                    <p>ymcity同城</p>\n" +
                        "\t\t\t\t\t<p align=\"right\">"+shijian+"</p>\n" +
                        "                </div>\n" +
                        "            </div>\n" +
                        "        </td>\n" +
                        "    </tr>\n" +
                        "    </tbody>\n" +
                        "</table>\n" +
                        "</body>\n")
                .setFromUser("1341475013@qq.com")
                .setToUser(mail)
                .setTitel("邮箱验证")
                .setUserName("1341475013@qq.com")
                .setPassword("wcbcbkvfcrqzibeh");
        try {
            Sendmail(mailBean);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}